package com.ziytek.web.citizen.config.caffeine;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.Scheduler;
import com.ziytek.web.citizen.configuration.PoolConfig;
import com.ziytek.web.citizen.model.bean.OfflineInfo;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

/**
 * caffeine缓存配置
 *
 * @author fengh
 */
@Slf4j
@Configuration
@EnableCaching
public class CacheConfig {
    @Value("${Caffeine.cache-expire.afterWriteMilliseconds}")
    private Long expireAfterWriteMilliseconds;
    @Value("${Caffeine.cache-expire.channelDays}")
    private Long expireChannelDays;


    @Bean
    public Cache<String, Object> caffeineCache() {
        return Caffeine.newBuilder()
                // 设置最后一次写入或访问后经过固定时间过期
                .expireAfterWrite(expireAfterWriteMilliseconds, TimeUnit.MILLISECONDS)
                // 初始的缓存空间大小
                .initialCapacity(100)
                // 缓存的最大条数
                .maximumSize(1000)
                .scheduler(Scheduler.forScheduledExecutorService(PoolConfig.EXECUTOR))
                .removalListener(CacheRemovalListener::onRemoval)
                .recordStats()
                .build();
    }

    @Bean
    public Cache<String, ChannelHandlerContext> caffeineCacheForChannel() {
        return Caffeine.newBuilder()
                // 设置最后一次写入或访问后经过固定时间过期
                .expireAfterWrite(expireChannelDays, TimeUnit.DAYS)
                // 初始的缓存空间大小
                .initialCapacity(100)
                // 缓存的最大条数
                .maximumSize(1000)
                .scheduler(Scheduler.forScheduledExecutorService(PoolConfig.EXECUTOR))
                .removalListener(CacheRemovalListener::onRemoval)
                .recordStats()
                .build();
    }

    @Bean
    public Cache<String, OfflineInfo> caffeineCacheOfflineInfo() {
        return Caffeine.newBuilder()
                // 设置最后一次写入或访问后经过固定时间过期
                .expireAfterWrite(expireAfterWriteMilliseconds, TimeUnit.MILLISECONDS)
                // 初始的缓存空间大小
                .initialCapacity(100)
                // 缓存的最大条数
                .maximumSize(1000)
                .scheduler(Scheduler.forScheduledExecutorService(PoolConfig.EXECUTOR))
                .removalListener(CacheRemovalListener::onRemoval)
                .recordStats()
                .build();
    }
}